package com.feng.controller;

import com.feng.entity.Test;
import com.feng.service.TestService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

//@RestController
@Controller
public class TestController {

    @Autowired
    private TestService testService;

    @Value("${aa.bb}")
    private String aabb;

    @Value("${cc.dd.ee}")
    private String cde;

    @GetMapping("/work")
    @ResponseBody
    public String test() {
        /*try {
            // 定义URL
            URL url = new URL("http://example.com/api/resource");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            conn.setRequestMethod("POST");

            // 设置请求头
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");

            // 启用输入输出流
            conn.setDoOutput(true);

            // JSON数据
            String jsonInputString = "{\"key1\":\"value1\", \"key2\":\"value2\"}";

            // 写入JSON数据到输出流
            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应码
            int responseCode = conn.getResponseCode();
            System.out.println("POST Response Code :: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
                // 处理响应...
            } else {
                // 错误处理...
            }

            // 断开连接
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        String s = testService.sendPost1();
        return s;
    }

    @GetMapping("/work2/{totals}/{sleeps}")
    @ResponseBody
    public String test2(@PathVariable int totals, @PathVariable int sleeps) throws InterruptedException {
        String s = testService.sendPost2(totals,sleeps);
        return s;
    }

    @GetMapping("/work3/{totals}/{sleeps}")
    public String test3(@PathVariable int totals, @PathVariable int sleeps,Model model) throws InterruptedException {
//        RedirectView redirectView = new RedirectView("/test5");
        System.out.println(totals+"--"+sleeps);
//        ModelMap model = new ModelMap();
        Test test = new Test();
        Gson gson = new Gson();
        List<String> list = new ArrayList<>();
        for (int i=1;i<=totals;i++) {
//            Thread.sleep(sleeps);
            test.setId(i);
            test.setName(i+"/"+totals);
            test.setKey1("key1_"+i);
            test.setKey2("key2_"+i);
//            String s = testService.sendPost3(i);
//            return redirectView;
            String json = gson.toJson(test);
            list.add(json);
        }
        model.addAttribute("list", list);
        model.addAttribute("sleeps", sleeps);
        model.addAttribute("totals", totals);
        System.out.println("model: "+model);
//        redirectView.setContextRelative(true);
//        redirectView.addStaticAttribute("list",list);
//        redirectView.addStaticAttribute("totals",totals);
//        redirectView.addStaticAttribute("sleeps",sleeps);
        return "forward:/test5";
    }

    @ResponseBody
    @GetMapping("/work4/{totals}/{sleeps}")
    public Flux<String> test4(@PathVariable int totals, @PathVariable double sleeps){
        Test test = new Test();
        Gson gson = new Gson();
        List<String> list = new ArrayList<>();
        for (int i=1;i<=totals;i++) {
//            Thread.sleep(sleeps);
            test.setId(i);
            test.setName(i+"/"+totals);
            test.setKey1("key1_"+i);
            test.setKey2("key2_"+i);
//            String s = testService.sendPost3(i);
//            return redirectView;
            String json = gson.toJson(test);
            list.add(json);
        }
        return Flux.fromStream(list.stream())
                .delayElements(Duration.ofMillis((long) (sleeps * 1000))); // 将秒转换为毫秒
    }

    @ResponseBody
    @GetMapping(value = "/test5", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamEvents(Model model) {//@RequestParam int totals, @RequestParam int sleeps, @RequestParam String list,
        List<String> list = (List<String>)model.getAttribute("list");
        System.out.println("list: "+list);
//        int totals = (int)model.getAttribute("totals");
        int sleeps = (int)model.getAttribute("sleeps");
        // 使用Flux创建事件流，每隔一秒发送一条消息
//        List<String> list1 = (List<String>)list;
        return Flux.fromStream(list.stream())
                .delayElements(Duration.ofSeconds(sleeps*1000)); // 控制发送频率
//                .map(this::toJson); // 将每个元素转换为 JSON 字符串
    }

    @ResponseBody
    @GetMapping("/yml")
    public String yml(){
//        return aabb;
        return cde;
    }
}
